package com.rjhch.tonglink.client.jms.pub_sub;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;

public class TopicPubSub {
    public static final String tcf = "tongtech.jms.jndi.JmsContextFactory";/* initial context factory*/
 
    public static final String remoteURL = "tlq://127.0.0.1:10025";
    public static final String remoteFactory = "RemoteConnectionFactory";

	public static void main(String[] args) {
  
		ConnectionFactory testConnFactory = null;
		Connection myConn = null;
		Session mySession = null;
		Topic testTopic = null;
		MessageProducer testProducer = null;
		MessageConsumer testConsumer = null;
		MessageConsumer anotherTestConsumer = null;
		TextMessage testMessage = null;

		try {
			testConnFactory = new com.tongtech.tmqi.ConnectionFactory();
			testTopic = new com.tongtech.tmqi.Topic("topic1");
			myConn = testConnFactory.createConnection();
			mySession = myConn.createSession(false, Session.AUTO_ACKNOWLEDGE);
			testProducer = mySession.createProducer(testTopic);
			testConsumer = mySession.createConsumer(testTopic);
			anotherTestConsumer = mySession.createConsumer(testTopic);
			testMessage = mySession	.createTextMessage("TopicPubSub Message");
			myConn.start();
			
			System.out.println("发送消息...");
			testProducer.send(testMessage);
			System.out.println("发送完成...");
			Message msg = testConsumer.receive(1000);
			if(msg != null){
				if(msg instanceof TextMessage){
					TextMessage message = (TextMessage)msg;
					System.out.println("testConsumer收到Text消息:"+message.getText());
				}else{
					System.out.println("testConsumer收到非Text消息.");
				}
			}
			msg = anotherTestConsumer.receive(1000);
			if(msg != null){
				if(msg instanceof TextMessage){
					TextMessage message = (TextMessage)msg;
					System.out.println("anotherTestConsumer收到Text消息..."+message.getText());
				}else{
					System.out.println("anotherTestConsumer收到非Text消息...");
				}
			}else{
				System.out.println("没有收到消息");
			}

		} catch (Exception jmse) {
			System.out.println("Exception oxxurred :" + jmse.toString());
			jmse.printStackTrace();
		} finally {
			try {
				if (mySession != null) {
					mySession.close();
				}
				if (myConn != null) {
					myConn.close();
				}
			} catch (Exception e) {
				System.out.println("退出时发生错误。");
				e.printStackTrace();
			}
		}

	}


}
